package com.lhh.virus.controller;

import com.lhh.virus.pojo.CountryVirusStats;
import com.lhh.virus.service.VirusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Auther 虎
 * @Data 2020/5/9 11:55
 * @Version 1.0
 */
@Controller
public class VirusController {
    @Autowired
    VirusService virusService;

    public static void sort(int[] array,int who[], int left, int right) {
        if(left > right) return;
        int base = array[left],base1=who[left];
        int i = left, j = right,tmp,p;
        while(i != j) {
            while(array[j] <= base && i < j) j--;
            while(array[i] >= base && i < j) i++;
            if(i < j) {
                tmp = array[i];array[i] = array[j];array[j] = tmp;
                p = who[i];who[i]=who[j];who[j]=p;
            }
        }
        array[left] = array[i];array[i] = base;
        who[left]=who[i];who[i]=base1;
        sort(array, who,left, i - 1);
        sort(array, who,i + 1, right);
    }

    @RequestMapping({"/virus/{country}","/virus"})
    public String virus(Model model,@PathVariable(required = false)  String country){
        List<CountryVirusStats> countryVirusStats=virusService.getAllCountryVirusStats();
        model.addAttribute("countryVirusStats",countryVirusStats);
        model.addAttribute("country",country);
        int total[]=new int[300];
        int who[]=new int[300];
        int j=0,i=0;
        for(i=0,who[0]=0;i<countryVirusStats.size()-1;i++){
            total[j]=total[j]+countryVirusStats.get(i).getLatestTotalCases();
            if(!countryVirusStats.get(i).getCountry().equals(countryVirusStats.get(i+1).getCountry())){
                j++;who[j]=i+1;
            }
        }
        total[j]=total[j]+countryVirusStats.get(i).getLatestTotalCases();
        model.addAttribute("sum",j);
        sort(total,who,0,j);
        model.addAttribute("total",total);
        model.addAttribute("who",who);
        return "virus";
    }
}
